"use strict";
import React from "react";
import { fromJS, is } from "immutable";
declare let window: any;
export default class AdScreenBottomBar extends React.Component<any, any> {
  slider: any = "";
  slideRef: any = "";
  sliderWrap: any = "";
  static displayName = "AdScreenBottomBar";

  /**
   * 绑定自定义事件
   */
  componentDidMount() {
    this.initSlider();
  }

  shouldComponentUpdate(nextProps) {
    return (
      !(is(nextProps.items, this.props.items) && is(nextProps.style, this.props.style)) ||
      nextProps.dataWidgetPath !== this.props.dataWidgetPath
    );
  }

  componentDidUpdate() {
    this.slider.destroy();
    this._removeDot();
    this.initSlider();
  }

  componentWillUnmount() {
    this.slider.destroy();
    this._removeDot();
  }

  render() {
    const { items, style, top, dataWidgetPath, ENV_EDITING } = this.props;

    return (
      <div className="isliderContent x-site-weixin-head-mt">
        <div
          className={`size-default-${ENV_EDITING ? "eidt" : "display"}`}
          ref={slider => (this.sliderWrap = slider)}
        >
          <div
            className={`size-default-${ENV_EDITING ? "eidt" : "display"}`}
            id="isliderArea"
            ref={slider => (this.slideRef = slider)}
          />
        </div>
      </div>
    );
  }

  _removeDot() {
    const elements = this.sliderWrap.getElementsByClassName("islider-dot-wrap");
    for (let i = 0, iLen = elements.length; i < iLen; i++) {
      elements[i].remove();
    }
  }

  /*
     * 初始化轮播
     */
  initSlider = () => {
    const { style } = this.props;
    const init = () => {
      const iSlider = window.iSlider;
      const plugins: any[] = [];
      // 加入轮播点的配置
      plugins.push([style.get("dot")]);
      let animateType = style.get("animateType");
      if (animateType === "default") animateType = "normal"; // 兼容老数据
      this.extendISliderAnimate();
      this.slider = new iSlider({
        // isDebug: true,
        isAutoplay: 1,
        isLooping: 1,
        isOverspread: 1,
        isTouchable: false,
        animateType,
        duration: 6000,
        animateTime: 900,
        dom: this.slideRef,
        data: this._getDataSource(),
        plugins
      });
    };
    // 异步加载islider的js
    if (!window.iSlider) {
      this.loadSlider().then(init);
    } else {
      init();
    }
  };

  extendISliderAnimate = () => {
    const iSlider = window.iSlider;
    iSlider.extend(iSlider._animateFuncs, {
      // none
      none: (() => {
        const fade: any = (dom, axis, scale, i, offset, direct) => {
          // console.log(dom, axis, scale, i, offset, direct);
          dom.style.zIndex = i === 1 ? 1 : 0;
        };

        fade.effect = "display";
        return fade;
      })(),
      // drop
      drop: (() => {
        const drop: any = (dom, axis, scale, i, offset, direct) => {
          // console.log(dom, axis, scale, i, offset, direct);
          dom.style.zIndex = i === 1 ? 1 : 0;
          switch (i) {
            case 0:
              iSlider.setStyle(dom, "transform", `translateY(0%)`);
              break;
            case 1:
              iSlider.setStyle(dom, "transform", `translateY(0)`);
              break;
            case 2:
              iSlider.setStyle(dom, "transform", `translateY(-100%)`);
              break;
          }
        };

        drop.effect = iSlider.styleProp("transform");
        drop.reverse = true;
        return drop;
      })(),
      // wipe
      wipe: (() => {
        const wipe: any = (dom, axis, scale, i, offset, direct) => {
          // console.log(dom, axis, scale, i, offset, direct);
          dom.style.zIndex = i === 1 ? 2 : 1;
          switch (i) {
            case 0: // next
              iSlider.setStyle(dom, "transform", `translateX(${0}px)`);
              break;
            case 1: // active
              iSlider.setStyle(dom, "transform", `translateX(${0}px)`);
              break;
            case 2: // prev
              iSlider.setStyle(dom, "transform", `translateX(${scale + offset}px)`);
              break;
          }
        };

        wipe.effect = iSlider.styleProp("transform");
        return wipe;
      })(),

      zoomout: (() => {
        const zoomout: any = (dom, axis, scale, i, offset, direct) => {
          console.log(dom, axis, scale, i, offset, direct);
          dom.style.zIndex = i === 1 ? 2 : 1;
          switch (i) {
            case 0: // next
              iSlider.setStyle(dom, "transform", `scale(2)`);
              break;
            case 1: // active
              iSlider.setStyle(dom, "transform", `scale(1)`);
              break;
            case 2: // prev
              iSlider.setStyle(dom, "transform", `scale(0.5)`);
              break;
          }
        };

        zoomout.effect = iSlider.styleProp("transform");
        return zoomout;
      })()
    });
  };

  _getDataSource() {
    let { items } = this.props;
    const wh100 = `display:block;width:100%;height:100%`;
    // 添加默认图片
    if (items.isEmpty()) {
      items = items.push({
        // tslint:disable-next-line:max-line-length
        content: `<a style="${wh100}" href="#"><img style="${wh100}" src="http://img.1000.com/qm-a-img/test2/01/1febbf4b7e3f7aaec3ef9b5a6ba211b3.jpg@712w_712h.png" /></a>`
      });
    }
    return fromJS(items)
      .toJS()
      .map(v => ({
        content: `<a style="${wh100}" href=${v.imgHref ||
          "#"}><img style="${wh100}" src=${this._wrapUrl(v)} /></a>`
      }));
  }

  /**
   * 包装地址
   * @param data
   * @private
   */
  _wrapUrl(data) {
    const oSrc = data.content;
    const cleanSrc: any = this.cleanUrl(oSrc);
    const { formatToJPG } = this.props;
    if (formatToJPG) {
      return this.format(cleanSrc, "jpg");
    }
    return oSrc;
  }

  cleanUrl = src => {
    src = src || "";
    const p = src.lastIndexOf("@");
    if (p !== -1) {
      return src.substring(0, p);
    }
    return src;
  };

  format = (src, format) => {
    const { mode, width, height, formatToJPG, devicePixelRatio } = this.props;

    const f = [src, "?x-oss-process=image"];
    f.push("/resize");
    if (width || height) {
      if (mode) {
        f.push(`,m_${mode}`);
      }
      if (width) {
        f.push(`,w_${Math.round(parseInt(width, 10) * devicePixelRatio)}`);
      }
      if (height) {
        f.push(`,h_${Math.round(parseInt(height, 10) * devicePixelRatio)}`);
      }
    } else {
      f.push(`,w_960`);
    }
    if (format) {
      // 加入锐化效果，增加清晰度
      f.push("/sharpen,100");
      f.push(`/format,${format}`);
    }
    return f.join("");
  };

  loadSlider = () => {
    const CDN_URL =
      "https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/x-site-ui-wechat/statics/javascript/";
    return this.loaderJs(CDN_URL + "iSlider.min.js").then(
      Promise.all([
        this.loaderJs(CDN_URL + "iSlider.animate.min.js"),
        this.loaderJs(CDN_URL + "iSlider.plugin.dot.min.js")
      ])
    );
  };

  /**
   * 异步加载js
   */
  loaderJs = (jsSrc): any => {
    return new Promise((resolve, reject) => {
      const head = document.getElementsByTagName("head")[0];
      const script = document.createElement("script");
      script.type = "text/javascript";
      script.charset = "utf-8";
      script.async = true;
      script.src = jsSrc;
      head.appendChild(script);

      script.onload = () => {
        resolve();
      };

      script.onerror = err => {
        reject(err);
      };
    });
  };

  /**
   * 异步加载css
   */
  loaderCss = cssSrc => {
    return new Promise((resolve, reject) => {
      const node = document.createElement("link");
      node.rel = "stylesheet";
      node.type = "text/css";
      node.href = cssSrc;
      node.onload = () => {
        resolve();
      };
      node.onerror = err => {
        reject(err);
      };
      document.getElementsByTagName("head")[0].appendChild(node);
    });
  };
}
